/**
 * @author mapeng
 * @version 2017-06-02
 */
;(function(doc, win) {
  var queryShopController = null;
  $(doc).on("pageInit", "#myPage", function(
    e,
    pageId,
    $page,
    isBack,
    isForward
  ) {
    queryShopController = new QueryShopController();
    if (isBack || isForward) {

      return;
    }
    var user = sessionStorageClient.getJSON("user");
    var authMinusData = {};
    if (user && user.authMinus) {
      authMinusData = getOAuthMinus(authMinusData, user.authMinus); //获取权限项
    }
    authority(authMinusData);
    initData4Page();
  });
  bindEvent4Page();
  var timeId;
  function initData4Page() {
    CommonUtil.sendJsonpRequest({
      url: App.serverUrl + "/app/employee/info.do",
      params: {},
      success: function(result) {
        if (result.success.toString() == "true") {
          //success
          CommonUtil.render(
            $("#myPage .big-header .user-info"),
            "myTPL",
            { data: result.resultObject, utils: CommonUtil },
            false
          );
        } else {
          //business error
          DialogUtil.dialogWarn(result.msg);
        }
      },
      error: function() {
        //not 200
        DialogUtil.dialogWarn("请求失败，请稍候重试");
      }
    });
  }

  function getOAuthMinus(result, authMinus) {
    var minusHtml = [];
    var indexCode = [];
    if (authMinus != null && authMinus.length > 0) {
      for (var i = 0; i < authMinus.length; i++) {
        var minus = authMinus[i];
        minusHtml.push(minus.taskCode);
        if (minus.taskCode == "app.my") {
          //我的权限项
          if (minus.children != null && minus.children.length > 0) {
            for (var i = 0; i < minus.children.length; i++) {
              indexCode.push(minus.children[i].taskCode);
            }
          }
        }
      }
      result.minusHtml = minusHtml;
    }
    result.indexCode = indexCode;
    return result;
  }
  function authority(authMinusData) {
    //判断查询功能模块权限
    if ($.inArray("app.marketingcenter", authMinusData.minusHtml) > -1) {
      //判断是否可以查看营销中心模块
      $("#myPage .marketingcenter").show(); //显示模块
    } else {
      $("#myPage .marketingcenter").hide(); //隐藏模块
    }
    if ($.inArray("app.order", authMinusData.minusHtml) > -1) {
      //判断是否可以查看订单
      $("#myPage .order").show(); //显示模块
    } else {
      $("#myPage .order").hide(); //显示模块
    }
    //判断操作权限
    if ($.inArray("app.shop.manage", authMinusData.indexCode) > -1) {
      //操作门店管理
      $("li[name='storeManage']").show(); //显示模块
    } else {
      $("li[name='storeManage']").hide(); //隐藏模块
    }
    if ($.inArray("app.staff.manage", authMinusData.indexCode) > -1) {
      //操作员工管理
      $("li[name='employeeManage']").show(); //显示模块
    } else {
      $("li[name='employeeManage']").hide(); //隐藏模块
    }
    if ($.inArray("app.machinesmanagement", authMinusData.indexCode) > -1) {
      //操作机具管理
      $("li[name='machineManage']").show(); //显示模块
    } else {
      $("li[name='machineManage']").hide(); //隐藏模块
    }
    if ($.inArray("app.me.servicemarket", authMinusData.indexCode) > -1) {
      //操作服务市场管理
      $("li[name='serviceMarket']").show(); //显示模块
    } else {
      $("li[name='serviceMarket']").hide(); //隐藏模块
    }
    //  if($.inArray("app.me.setting", authMinusData.indexCode) > -1 ){ //操作设置
    //     $("li[name='settings']").show();//显示模块
    //  }else{
    //     $("li[name='settings']").hide();//隐藏模块
    //  }
  };
  function checkedUserJump(succ) {
    if (window.loadingFlag) {
      return;
    }
    window.loadingFlag = true;

    setTimeout(function() {
      window.loadingFlag = false;
    }, 1000 * 2);
    var user =sessionStorageClient.getJSON('user');
    if(user && user.role==1 && user.isHaveShop){
      succ();
      return;
    }
    var serverUrl = App.serverUrl + "merchantApp/index/queryUserData.do";
    var sucFunc = function(result) {
      if (String(result.success) == "true") {
        var user = result.resultObject;
        sessionStorageClient.putJSON("user", user);
        var user = sessionStorageClient.getJSON("user");
        if (user.role == 1 && !user.isHaveShop) {
          queryShopController.confirmShop(succ);
        } else {
          succ();
        }
      }
    };
    CommonUtil.sendJsonpRequest({
      url: serverUrl,
      success: sucFunc,
      useDefaultLoading: false
    });
  }
  function bindEvent4Page() {
    //个人信息
    $(document).on("click", "#myPage .big-header .right-icon", function(e) {
      $.router.load("my_detail.html", true);
    });
    window.loadingFlag = false;
    //门店管理
    $(document).on(
      "click",
      "#myPage li.option-item[name='storeManage']",
      function(e) {
        //新版
        var bindSuccess = function() {
          var url = "vuepages/index.html#/storeManage";
          AppUtil.call(AppUtil.APIS.PUSH_WINDOW, {
            url: url,
            suffixParams: "",
            target: "local",
            param: {
              title: null
            }
          });
        };
        checkedUserJump(bindSuccess);
      }
    );

    //员工管理
    $(document).on(
      "click",
      "#myPage li.option-item[name='employeeManage']",
      function(e) {
        var bindSuccess = function() {
          $.router.load("employee_manage.html", true);
        };
        checkedUserJump(bindSuccess);
      }
    );

    //机具管理
    $(document).on(
      "click",
      "#myPage li.option-item[name='machineManage']",
      function(e) {
        var user = sessionStorageClient.getJSON("user");
        var bindSuccess = function() {
          //$.router.load("machines_manage.html", true);
          AppUtil.call(AppUtil.APIS.PUSH_WINDOW,
            {
                url: 'vuepages/index.html#/machinesManage',
                target: 'local',
                param: {
                    title: null
                }
            });        };
        checkedUserJump(bindSuccess);
      }
    );
    //语音播报
    $(document).on(
      "click",
      "#myPage li.option-item[name='voiceBroadcast']",
      function(e) {
        var bindSuccess = function() {
          AppUtil.call(AppUtil.APIS.PUSH_WINDOW, {
            url: "vuepages/index.html#/voice",
            target: "local",
            param: {
              title: null
            }
          });
        };
        checkedUserJump(bindSuccess);
      }
    );

    //服务市场
    $(document).on(
      "click",
      "#myPage li.option-item[name='serviceMarket']",
      function(e) {
        var $this = $(this);
        if (!$this.hasClass("hasClick")) {
          checkOAuthCode();
          clearTimeout(timeId);
          timeId = setTimeout(function() {
            $this.removeClass("hasClick");
          }, 2000);
          $this.addClass("hasClick");
        }
      }
    );

    //设置
    $(document).on("click", "#myPage li.option-item[name='settings']", function(
      e
    ) {
      // $.router.load("mine-setting.html", true);
      var url = "vuepages/index.html#/setting";
          AppUtil.call(AppUtil.APIS.PUSH_WINDOW, {
            url: url,
            suffixParams: "",
            target: "local",
            param: {
              title: null
            }
          });
    });
  }
  var checkOAuthCode = function() {
    //请求bmserver获取授权码
    var serverUrl = App.serverUrl + "serviceMarket/checkAuthToken.do";
    var sucFunc = function(result) {
      common.closeLoading();
      if (String(result.success) == "true") {
        var serviceMarketUrl =
          App.bmwServiceUrl + "?" + App.urlParam + "#/serviceMarket";
        AppUtil.call(AppUtil.APIS.PUSH_WINDOW, {
          url: serviceMarketUrl,
          target: "server",
          param: {
            title: {
              title: "服务市场",
              color: "#333333",
              background: "#ffffff"
            }
          }
        });
      } else {
        var toAuthorizeUrl =
          App.bmwServiceUrl + "?" + App.urlParam + "#/toAuthorize";
        AppUtil.call(AppUtil.APIS.PUSH_WINDOW, {
          url: toAuthorizeUrl,
          target: "server",
          param: {
            title: {
              title: "去授权",
              color: "#333333",
              background: "#ffffff"
            }
          }
        });
      }
      $("#myPage li.option-item[name='serviceMarket']").removeClass("hasClick");
    };

    var failFunc = function() {
      common.closeLoading();
      log4JS.info("getOAuthCode failed. http status not 200");
      DialogUtil.dialogWarn();
      $("#myPage li.option-item[name='serviceMarket']").removeClass("hasClick");
    };
    CommonUtil.sendJsonpRequest({
      url: serverUrl,
      success: sucFunc,
      error: failFunc,
      params: null,
      useDefaultLoading: true
    });
  };
  $(document).on("click","#myPage #linkToIndex",function(e){
    window.location.href = '../vuepages/index.html#/?'+window.App.urlParam;
  });
})(document,window);
